<template>
  <ElPopover
    ref="popover"
    :width="popoverWidth"
    :placement="placement"
    :reference="reference"
    popper-class="fa-widget-popover fa-contract-scope"
    @after-leave="afterClose"
  >
    <SignSelect v-bind="$props" v-on="$listeners" />
  </ElPopover>
</template>

<script lang="ts">
import { computed, defineComponent, PropType, toRefs } from 'vue'
import SignSelect from './SignSelect.vue'
import usePopover from '@/utils/compositions/usePopover'
import { Viewer, SignData, SignType } from '@/types'
import { Widget } from '@/models'

/** 签章选择弹出层 */
export default defineComponent({
  name: 'FaSignSelectPop',

  components: { SignSelect },

  props: {
    /**
     * 类型
     * 可选值：seal 印章（默认）；signature 签名
     */
    type: {
      type: [String, Number] as PropType<SignType | string>,
      default: SignType.SEAL
    },

    /** 印章、签名数据 */
    data: {
      type: Array as PropType<SignData[]>,
      default: () => []
    },

    /** 是否允许拖拽 */
    draggable: {
      type: Boolean,
      default: false
    },

    /** 签章自定义 class */
    signClassName: Function as PropType<(sign: SignData) => string | void>,

    /** 位置 */
    placement: {
      type: String,
      default: 'right-start'
    },

    /** 触发节点 */
    reference: {
      type: HTMLElement as PropType<HTMLElement | null>
    },

    /** 文档查看组件 */
    viewer: {
      type: Object as PropType<Viewer | null>
    },

    /** 当前操作控件 */
    widget: {
      type: Object as PropType<Widget>
    }
  },

  setup(props, { emit }) {
    return {
      ...toRefs(usePopover(emit)),

      /** 弹出层宽度，用以数据量较大多列展示 */
      popoverWidth: computed(() => {
        /** 列宽 */
        const colW = 160

        /** 最大列数 */
        const max = 3

        /** 最小宽度 */
        const minW = 220

        /** 列数，按 4 个每列排 */
        const cols = Math.min(Math.ceil(props.data.length / 4), max)

        return Math.max(cols * colW, minW)
      })
    }
  }
})
</script>
